/*
 *英才会硕信息科技有限公司拥有本软件的版权，拥有本软件版权2025   并保留所有权利。
 *Copyright 2021,YCHS Information&Science Technology Co.,Ltd,
 *All rights reserved.
 */
package com.ychs.lawyerback01.util;

import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.FileCopyUtils;


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @author xuehongjin
 * @version 1.0
 * @date 2025/8/29
 */
public class FileDownloadUtil {

    public static void downloadTemplate(HttpServletResponse response, String templateFileName, String downloadFileName) throws IOException {
        // 1. 读取resources/templates目录下的“指定文件”（templateFileName就是你传的目标文件名）
        Resource resource = new ClassPathResource("templates/" + templateFileName);
        if (!resource.exists()) {
            throw new IOException("指定的模板文件不存在：" + templateFileName); // 明确提示文件不存在
        }

        // 2. 设置响应头（确保前端能正确识别为Word文件并下载）
        response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"); // .docx格式MIME
        response.setCharacterEncoding("UTF-8");
        // 处理中文文件名乱码
        String encodedFileName = URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8.name());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        // 3. 把文件流写入响应，返回给前端
        try (InputStream inputStream = resource.getInputStream();
             OutputStream outputStream = response.getOutputStream()) {
            FileCopyUtils.copy(inputStream, outputStream);
            outputStream.flush();
        }
    }
}